/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="../base/lcc.ts" />
/// <reference path="../utils/js.ts" />
/// <reference path="../log/log-manager.ts" />
/// <reference path="./redis-client.ts" />

namespace lcc {

const TAG = "lcc/redis/redis-manager.ts";

/**
 * @zh
 * Redis tick时间
 */
export let REDIS_TICKTIME = 1;

/**
 * @zh
 * Redis客户端映射表
 */
export let REDISCLIENTS:{[key:string]:RedisClient} = js.createMap();

/**
 * @zh
 * Redis管理器<br/>
 */
class RedisManager {
	
	/**
     * @zh
	 * 是否使用心跳
	 */
	private _useHeart:boolean = false;

	/**
     * @zh
	 * 安装心跳
	 */
	private setupHeartTick(){
		if(!this._useHeart && !js.isEmptyMap(REDISCLIENTS)){
			timerMgr.addTimer(REDIS_TICKTIME, this.onHeartTick.bind(this),{
                group : "lcc.RedisManager", 
                key : "tick",
                loop : true
            });
			this._useHeart = true;
			DEBUG.REDIS && logMgr.debug(TAG, `setupHeartTick tick ${REDIS_TICKTIME}`);
		}
	}

	/**
     * @zh
	 * 删除心跳
	 */
	private deleteHeartTick(){
		if(this._useHeart && js.isEmptyMap(REDISCLIENTS)){
			timerMgr.removeTimer({
                group : "lcc.RedisManager", 
                key : "tick"
            });
			this._useHeart = false;
			DEBUG.REDIS && logMgr.debug(TAG, `deleteHeartTick tick`);
		}
	}
	
	/**
     * @zh
	 * 心跳回调
	 */
	private onHeartTick(dt:number){
		for (let rdsname of Object.keys(REDISCLIENTS)){
			let redisClient = REDISCLIENTS[rdsname];
			if(redisClient){
				redisClient.onUpdate(dt);
			}
		}
	}
    
	/**
     * @zh
	 * 添加Redis客户端
     * 
	 * @param rdsname - Redis名称
	 * @param options - 类型
	 */
	public addClient(rdsname:string, options:RedisOptions = {}){
		DEBUG.REDIS && logMgr.debug(TAG, `addClient ${rdsname} ${JSON.stringify(options)}`);
		if(REDISCLIENTS[rdsname]){
			logMgr.error(TAG, `redis [${rdsname}] conflict!`);
		}else{
			let redisClient = new RedisClient(rdsname, options);
			REDISCLIENTS[rdsname] = redisClient;
			this.setupHeartTick();
			DEBUG.REDIS && logMgr.debug(TAG, `addClient ${rdsname} success`);
			return redisClient;
		}
	}

    /**
     * @zh
     * 获得指定Redis客户端
     * 
     * @param rdsname - Redis名称
     */
    public getClient(rdsname:string){
        return REDISCLIENTS[rdsname];
	}
	
	/**
     * @zh
	 * 移除指定Redis客户端
     * 
	 * @param rdsname - Redis名称
	 */
	public removeClient(rdsname:string){
		DEBUG.REDIS && logMgr.debug(TAG, `removeClient ${rdsname}`);
		let redisClient = REDISCLIENTS[rdsname];
		if(redisClient){
			delete REDISCLIENTS[rdsname];
			redisClient.disconnect();
			this.deleteHeartTick();
			DEBUG.REDIS && logMgr.debug(TAG, `removeClient ${rdsname} success`);
		}
	}
    
    /**
     * @zh
     * 移除所有REDIS
     */
    public removeAllClients(){
        for(let rdsname of Object.keys(REDISCLIENTS)){
            this.removeClient(rdsname);
        }
    }
};

/**
 * @zh
 * Redis管理器对象
 */
export const redisMgr = new RedisManager();

}
